﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.IO;
using System.Xml.Serialization;

namespace WSOAMOBIMIDWARE
{
    public class AppUtil
    {/// <summary>
        /// 序列化为xml文件
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <param name="filePath"></paLram>
        public static void SerializeXML<T>(T obj, string filePath)
        {
            FileStream fs = null;
            XmlSerializer xmlSerializer = null;
            try
            {
                fs = new FileStream(filePath, FileMode.OpenOrCreate);
                fs.SetLength(0);
                xmlSerializer = new XmlSerializer(typeof(T));
                xmlSerializer.Serialize(fs, obj);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                throw;
            }
            finally
            {
                if (fs != null)
                    fs.Close();
                xmlSerializer = null;
            }

        }
        /// <summary>
        /// 反序列化xml文件
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <param name="filePath"></param>
        public static T DeSerializeXML<T>(string filePath) where T : class
        {
            T obj = null;
            if (File.Exists(filePath))
            {
                FileStream fs = null;
                XmlSerializer xmlSerializer;
                try
                {
                    fs = new FileStream(filePath, FileMode.Open);
                    xmlSerializer = new XmlSerializer(typeof(T));
                    obj = (T)xmlSerializer.Deserialize(fs);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    throw;
                }
                finally
                {
                    if (fs != null)
                        fs.Close();
                    xmlSerializer = null;
                }
            }
            return obj;
        }
    }
}
